package com.zhidao.backend.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhidao.backend.common.StatusCode;
import com.zhidao.backend.entity.Learn;
import com.zhidao.backend.exception.BusinessException;
import com.zhidao.backend.mapper.LearnMapper;
import com.zhidao.backend.service.ILearnService;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class LearnServiceImpl extends ServiceImpl<LearnMapper, Learn> implements ILearnService {
    @Override
    public void learnRoute(Long userId, Long routeId) {
        Learn learn = new Learn();
        learn.setUserId(userId);
        learn.setRouteId(routeId);
        learn.setProgress(0);
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        learn.setUpdateTime(timestamp);
        learn.setDeleted(false);
        if (!this.save(learn)) {
            throw new BusinessException(StatusCode.SYSTEM_ERROR.getCode(), "学习失败");
        }
    }

    @Override
    public void cancelLearnRoute(Long userId, Long routeId) {
        int res = baseMapper.delete(new QueryWrapper<Learn>().eq("user_id", userId).eq("route_id", routeId));
        if (res < 1) {
            throw new BusinessException(StatusCode.SYSTEM_ERROR.getCode(), "取消学习失败");
        }
    }

    @Override
    public void updateProgress(Long userId, Long routeId, Integer progress) {
        Learn learn = new Learn();
        learn.setProgress(progress);
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        learn.setUpdateTime(timestamp);
        int res = baseMapper.update(learn, new QueryWrapper<Learn>().eq("user_id", userId).eq("route_id", routeId));
        if (res < 1) {
            throw new BusinessException(StatusCode.SYSTEM_ERROR.getCode(), "更新学习进度失败");
        }
    }

    @Override
    public Map<Long, Integer> getLearnRoutes(Long id) {
        List<Learn> learns = this.list(new QueryWrapper<Learn>().eq("user_id", id).orderByDesc("update_time"));
        //如果没有学习记录，返回空map
        if (learns == null || learns.size() == 0) {
            return null;
        }
        return learns.stream().collect(Collectors.toMap(Learn::getRouteId, Learn::getProgress));
    }

    @Override
    public Boolean isLearn(Long userId, Long routeId) {
        Learn learn = this.getOne(new QueryWrapper<Learn>().eq("user_id", userId).eq("route_id", routeId));
        return learn != null;
    }
}
